package org.feidao.chapter91.elasticSearch;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created by linghufeixia on 2023-2-18.
 * Elasticsearc document工具类
 */
@Component
public class IndexUtil {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引index
     * @param index
     * @return
     * @throws IOException
     */
    public boolean createIndex(String index){
        if (!isIndexExist(index)) {
            return false;
        }
        boolean isAcknowledged = false;
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
        try {
            AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            isAcknowledged = acknowledgedResponse.isAcknowledged();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return isAcknowledged;
        }
    }

    /**
     * 删除索引
     * @param index
     * @return
     * @throws IOException
     */
    public boolean deleteIndex(String index){
        if (!isIndexExist(index)) {
            return false;
        }
        boolean isAcknowledged = false;
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
        try {
            AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);
            isAcknowledged = acknowledgedResponse.isAcknowledged();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return isAcknowledged;
        }
    }

    /**
     * 判断索引是否存在
     * @param index
     * @return
     * @throws IOException
     */
    public boolean isIndexExist(String index) {
        boolean isExist = false;
        try {
            GetIndexRequest getIndexRequest = new GetIndexRequest(index);
            isExist = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return isExist;
        }
    }
}
